<template>
  <div class="app-container">
    <!-- 保存按钮 -->
    <el-row :gutter="10" class="mb8"  style="justify-content: end; align-items: center;">
      <h1 style="margin-right: auto;">{{ drugOutTitle }}</h1>
      <el-col :span="1.5" v-if="drugOutTitle=='新增出库信息'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="submitForm"
        >提交审核</el-button>
      </el-col>
      <el-col :span="1.5" v-if="drugOutTitle=='新增出库信息'">
        <el-button
          type="success"
          plain
          icon="Edit"
          @click="directPut"
        >直接出库</el-button>
      </el-col>

      <el-col :span="1.5" v-if="drugOutTitle =='出库详情-待审核'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="approve"
        >审核通过</el-button>
      </el-col>
      <el-col :span="1.5" v-if="drugOutTitle =='出库详情-待审核'">
        <el-button
          type="success"
          plain
          icon="Edit"
          @click="noApprove"
          >审核未通过</el-button>
      </el-col>         
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="goBack"
        >返回</el-button>
      </el-col>
    </el-row>

    <!-- 添加-未审核出库订单列表 -->
    <el-form ref="drugOutRef" :model="drugOutList" :rules="rules" label-width="80px" v-if="drugOutTitle == '新增出库信息'||drugOutTitle == '出库详情-待审核'">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="出库单号" prop="drugsOutId">
            <el-input v-model="drugOutList.drugsOutId" placeholder="请输入出库单号" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库日期" prop="drugsOutDate">
            <el-date-picker clearable
              v-model="drugOutList.drugsOutDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择出库日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库人员" prop="drugsOutStaff">
            <div v-if="drugOutTitle == '出库详情-待审核'">
              {{userList.find(item => item.userId == drugOutList.drugsOutStaff)?.nickName || '未知' }}
            </div>
           
            <el-select v-model="drugOutList.drugsOutStaff" placeholder="请选择出库人员" v-if="drugOutTitle == '新增出库信息'">
              <el-option
                v-for="dict in userList"
                :key="dict.drugsOutStaff"
                :label="dict.nickName"
                :value="dict.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库类型" prop="drugsOutType">
            <el-select v-model="drugOutList.drugsOutType" placeholder="请选择出库类型">
              <el-option label="科室领药" value='科室领药' />
              <el-option label="报损出库" value='报损出库' />
              <el-option label="采购退货" value='采购退货' />
              <el-option label="其他出库" value='其他出库' />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="制单人员" prop="drugsOutCreationStaff">
            <el-input v-model="drugOutList.drugsOutCreationStaff" placeholder="请输入制单人员" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="制单日期" prop="drugsOutCreationDate">
            <el-date-picker clearable
              v-model="drugOutList.drugsOutCreationDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择制单日期" disabled>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="drugOutList.remarks" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
<!-- 审核通过 或 审核未通过 状态-->
    <div class="order-info" v-if="drugOutTitle == '出库详情-审核通过' || drugOutTitle == '出库详情-审核未通过' " >
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>出库单号：</label>
              <div >{{ drugOutList.drugsOutId }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>出库日期：</label>
              <div>{{ drugOutList.drugsOutDate }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>出库人员：</label>
              {{userList.find(item => item.userId == drugOutList.drugsOutStaff)?.nickName || '未知' }}
     
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>入库类型：</label>
              <div>{{ drugOutList.drugsOutType }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>制单日期：</label>
              <div>{{ drugOutList.drugsOutCreationDate }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>制单人员：</label>
              <div>{{ drugOutList.drugsOutCreationStaff }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>入库备注：</label>
              <div>{{ drugOutList.remarks }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>审核时间：</label>
              <div>{{ drugOutList.auditDate }}</div>
              <!-- <el-input v-model="warehousing.auditDate" disabled/> -->
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>审核人员：</label>
              <div>{{ drugOutList.auditStaff }}</div>
              <!-- <el-input v-model="warehousing.auditStaff" disabled/> -->
            </div>
          </el-col>
        </el-row>
     </div> 
<!--  审核通过 或 审核未通过 未审核 状态 -->
  <div  v-if="drugOutTitle == '出库详情-审核通过'|| drugOutTitle == '出库详情-审核未通过' ||drugOutTitle == '出库详情-待审核'" >
    <el-table v-loading="loading" :data="outIntermediateList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <!-- <el-table-column label="入库订单号id" align="center" prop="drugsOutId" /> -->
      <el-table-column label="药品编码" align="center" prop="drugCode" />
      <!-- 遍历 drugList 当前的药品编码和药品列表中的药品编码一致时，显示药品名称  -->
      <el-table-column label="药品名称" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.drugGenericName}}
          </template>
      </el-table-column>
      <el-table-column label="生产厂家" align="center">
          <template #default="scope">
            <dict-tag :options="doctor_drug_manufacturer" :value='drugList.find(item => item.drugCode === scope.row.drugCode)?.drugManufacturer'/>
          </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="unit">
        <template #default="scope">
          <dict-tag :options="doctor_packaging_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="采购价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice}}
          </template>
      </el-table-column>
      <el-table-column label="零售价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice}}
          </template>
      </el-table-column>
      <el-table-column label="采购金额(元)" align="center" prop="purchaseAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="零售金额(元)" align="center" prop="retailAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice).toFixed(2) }}
          </template>
        </el-table-column>
    </el-table>
    <div style="padding: 20px;">
        采购金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalPurchaseAmount }}</text>元 零售金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalRetailAmount }}</text>元
    </div>
  </div>
<!-- 出库表单 -->
  <div  v-if="drugOutTitle=='新增出库信息'" >
    <el-table v-loading="loading" :data="outIntermediateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <!-- <el-table-column label="入库订单号id" align="center" prop="drugsOutId" /> -->
      <el-table-column label="药品编码" align="center" prop="drugCode" />
      <!-- 遍历 drugList 当前的药品编码和药品列表中的药品编码一致时，显示药品名称  -->
      <el-table-column label="药品名称" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.drugGenericName}}
          </template>
      </el-table-column>
      <el-table-column label="生产厂家" align="center">
          <template #default="scope">
            <dict-tag :options="doctor_drug_manufacturer" :value='drugList.find(item => item.drugCode === scope.row.drugCode)?.drugManufacturer'/>
          </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" >
        <template #default="scope">
          <el-input v-model="scope.row.quantity" :min="1" size="small" @change="updateAmounts(scope.row)"/>
          </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit">
        <template #default="scope">
          <dict-tag :options="doctor_packaging_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="采购价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice}}
          </template>
      </el-table-column>
      <el-table-column label="零售价(元)" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice}}
          </template>
      </el-table-column>
      <el-table-column label="采购金额(元)" align="center" prop="purchaseAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.purchasePrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="零售金额(元)" align="center" prop="retailAmount">
          <template #default="scope">
            {{ (scope.row.quantity * drugList.find(item => item.drugCode === scope.row.drugCode)?.retailPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center">
          <template #default="scope">
            {{drugList.find(item => item.drugCode === scope.row.drugCode)?.drugInventory}}
          </template>
        </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:outIntermediate:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="Delete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 20px;">
        采购金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalPurchaseAmount }}</text>元 零售金额合计：<text style="color: red;font-weight: 700;font-size: large;margin: 0 5px;">{{ totalRetailAmount }}</text>元
    </div>
    <div style="text-align: center;">
      <!-- 添加按钮 -->
      <el-button type="primary" icon="Plus" @click="handleAddDrug" >添加药品</el-button>
    </div>
     
  </div>
  
    <!-- 添加或修改药品入库和药品中间对话框 -->
    <el-dialog :title="Drugtitle" v-model="openDrug"  width="1000px" append-to-body>
      <el-scrollbar height="400px">
        <el-form :model="queryParamsDrug" :inline="true" label-width="68px">
          <el-form-item label="处方类别" prop="drugInformationId">
            <el-select v-model="queryParamsDrug.drugInformationId" placeholder="处方类别" clearable style="width: 100px">
              <el-option
                v-for="dict in informationList"
                :key="dict.id"
                :label="dict.drugInformationName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药品名称" prop="drugGenericName">
            <el-input
              v-model="queryParamsDrug.drugGenericName"
              placeholder="请输入药品名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="生产厂家" prop="drugManufacturer">
            <el-select v-model="queryParamsDrug.drugManufacturer" placeholder="请选择生产厂家" clearable style="width: 200px">
              <el-option
                v-for="dict in doctor_drug_manufacturer"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getDrugList">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="drugList" @selection-change="handleSelectionChangeDrug">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="id" />
          <el-table-column label="药品编码" align="center" prop="drugCode" />
          <el-table-column label="药品名称" align="center" prop="drugGenericName" />
          <el-table-column label="规格" align="center" prop="drugSpecification" />
          <el-table-column label="收费类别" align="center" prop="drugInformationId">
            <template #default="scope">
              {{informationList.find(item => item.id == scope.row.drugInformationId)?.drugInformationName || '未知' }}
            </template>
          </el-table-column>  
          <el-table-column label="生产厂家" align="center" prop="drugManufacturer">
            <template #default="scope">
              <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.drugManufacturer"/>
            </template>
          </el-table-column>
          <el-table-column label="采购价" align="center" prop="purchasePrice" />
          <el-table-column label="零售价" align="center" prop="retailPrice" />
        </el-table>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDrug">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OutIntermediate">
import { listOutIntermediate, getOutIntermediate, delOutIntermediate, addOutIntermediate, updateOutIntermediate } from "@/api/drug/outIntermediate";
import { listDrug, getDrug, delDrug, addDrug, updateDrug,selectDrugByCodes} from "@/api/drug/drug";
import { listInformation } from "@/api/drug/information";
import { listDrugOut, getDrugOut, delDrugOut, addDrugOut, updateDrugOut } from "@/api/drug/drugOut";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { doctor_packaging_unit,doctor_drug_manufacturer,doctor_drug_category,doctor_drug_usage} = proxy.useDict('doctor_packaging_unit','doctor_drug_manufacturer','doctor_drug_category','doctor_drug_usage');


const userList = ref([]);
const outIntermediateList = ref([]);
const drugList = ref([]);
const informationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const drugOutTitle = ref("");
const Drugtitle =ref("");
const openDrug = ref(false);
const drugIds = ref([]);

// 获取登陆用户信息
import useUserStore from '@/store/modules/user'
const user = useUserStore();

getUserList();
/** 查询用户列表 */
function getUserList() {
  loading.value = true;
  listUser({
    pageNum: 1,
    pageSize: 9999,
  }).then(res => {
    userList.value = res.rows;
    console.log(userList.value);
  });
};

const data = reactive({
  drugOut: {},
  drugOutList:{},
  form: {},
  queryParamsDrug:{
    pageNum: 1,
    pageSize: 9999,
    drugInformationId: null,
    drugCode: null,
    drugGenericName: null,
    drugManufacturer: null,
    drugStatus: null,
    creationTime: null,
    drugInventory:null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drugsOutId: null,
    drugCode: null,
    quantity: null,
    unit: null,
    purchaseAmount: null,
    retailAmount: null
  },
  rules: {
    drugsOutId: [
      { required: true, message: "出库单号不能为空", trigger: "blur" }
    ],
    drugsOutDate: [
      { required: true, message: "出库日期不能为空", trigger: "blur" }
    ],
    drugsOutStaff: [
      { required: true, message: "出库人员不能为空", trigger: "change" }
    ],
    drugsOutType: [
      { required: true, message: "出库类型不能为空", trigger: "change" }
    ],
    drugsOutCreationDate: [
      { required: true, message: "制单日期不能为空", trigger: "blur" }
    ],
    drugsOutCreationStaff: [
      { required: true, message: "制单人员不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules, queryParamsDrug,drugOutList } = toRefs(data);
// 修改接收方式为响应式处理
import { toRaw } from 'vue';

// 返回
function goBack() {
  proxy.$router.push({ 
    path: "/1/drugOut",
    query: { refresh: Date.now() }  // 添加随机参数强制刷新
  });
}
// 药品多选框选中数据
function handleSelectionChangeDrug(selection) {
  drugIds.value = selection.map(item => item.id);
}
// 计算属性
const totalPurchaseAmount = computed(() => {
  return outIntermediateList.value.reduce((sum, item) => sum + parseFloat(item.purchaseAmount || 0), 0).toFixed(2);
});

const totalRetailAmount = computed(() => {
  return outIntermediateList.value.reduce((sum, item) => sum + parseFloat(item.retailAmount || 0), 0).toFixed(2);
});
// 保存选择的药品
function submitFormDrug() {
  if (drugIds.value.length === 0) {
    proxy.$modal.msgWarning("请选择药品");
    return;
  }
  // 先判断是否有重复的药品编码 如果重复就去重
  // 创建临时Set存储已存在的药品编码
  const existingCodes = new Set(outIntermediateList.value.map(item => item.drugCode));
   // 过滤重复药品（保留最后一个出现的）
   const uniqueDrugs = drugIds.value.reduceRight((acc, drugId) => {
    const drug = drugList.value.find(d => d.id === drugId);
    if (drug && !existingCodes.has(drug.drugCode)) {
      existingCodes.add(drug.drugCode);
      acc.push(drug);
    }
    return acc;
  }, []).reverse();
   // 添加非重复药品
   uniqueDrugs.forEach(selectedDrug => {
    outIntermediateList.value.push({
      id: outIntermediateList.value.length + 1,
      drugsOutId: drugOutList.value.drugsOutId,
      drugCode: selectedDrug.drugCode,
      quantity: 1,
      unit: selectedDrug.packagingUnit,
      purchaseAmount: (1 * selectedDrug.purchasePrice).toFixed(2),
      retailAmount: (1 * selectedDrug.retailPrice).toFixed(2)
    });
  });
  // 清楚选择的药品
  drugIds.value = [];
  openDrug.value = false;
 }
 // 删除药品
function Delete(row) {
  const index = outIntermediateList.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    outIntermediateList.value.splice(index, 1);
    // 删除后重新排序序号
    outIntermediateList.value.forEach((item, idx) => {
      item.id = idx + 1;
    });
  }
}
 // 添加金额计算方法
const updateAmounts = (row) => {
  const drug = drugList.value.find(item => item.drugCode === row.drugCode);
  if (drug) {
    row.purchaseAmount = parseFloat((row.quantity * drug.purchasePrice).toFixed(2));
    row.retailAmount = parseFloat((row.quantity * drug.retailPrice).toFixed(2));
  }
}
/** 查询药品信息列表 */
function getDrugList() {
  loading.value = true;
  queryParamsDrug.value.params = {};
  listDrug(queryParamsDrug.value).then(response => {
    drugList.value = response.rows;
    console.log(drugList.value);
    loading.value = false;
  });
}
/** 查询药品信息分类列表 */
function getlistInformationList() {
  loading.value = true;
  listInformation(queryParams.value).then(response => {
    informationList.value = response.rows;
    // console.log(informationList.value);
    loading.value = false;
  });
}
// 药品添加按钮操作
function handleAddDrug(){
  openDrug.value = true;
  Drugtitle.value = "选择药品";
}
import { useRoute } from 'vue-router';
import { User } from "@element-plus/icons-vue";
const route = useRoute();
// 获取跳转信息
onMounted(() => {
  if(route.query.formData) {
    // 获取原始数据
    drugOutList.value = toRaw(JSON.parse(route.query.formData));
    // console.log(drugOutList.value);
    drugOutTitle.value = toRaw(route.query.title1);
    queryParams.value.drugsOutId = drugOutList.value.drugsOutId;
    getList();
  }
})

/** 查询药品入库和药品中间列表 */
function getList() {
  loading.value = true;
  listOutIntermediate(queryParams.value).then(response => {
    outIntermediateList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openDrug.value = false;
  reset();
}

// 表单重置
function reset() {
  drugOutList.value={
      id: null,
    drugsOutId: null,
    drugsOutDate: null,
    drugsOutStaff: null,
    drugsOutType: null,
    drugsOutCreationDate: null,
    drugsOutCreationStaff: null,
    remarks: null,
    totalPurchaseAmount: null,
    totalRetailAmount: null,
    auditStatus: null,
    auditDate: null,
    auditStaff: null
  }
  form.value = {
    id: null,
    drugsOutId: null,
    drugCode: null,
    quantity: null,
    unit: null,
    purchaseAmount: null,
    retailAmount: null
  };
  proxy.resetForm("outIntermediateRef");
  proxy.resetForm("drugOutRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品入库和药品中间";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOutIntermediate(_id).then(response => {
    drugOutList.value = response.data;
    open.value = true;
    title.value = "修改药品入库和药品中间";
  });
}

/** 提交审核 */
function submitForm() {
  drugOutList.value.totalPurchaseAmount=totalPurchaseAmount.value;
  drugOutList.value.totalRetailAmount=totalRetailAmount.value;
  drugOutList.value.auditStatus=0;
  if(outIntermediateList.value.length==0){
    proxy.$modal.msgWarning("请添加药品");
    return;
  }
  proxy.$refs["drugOutRef"].validate(valid => {
    if (valid) {
      addDrugOut(drugOutList.value).then(response => {
          outIntermediateList.value.forEach(item=>{
          const intermediateItem = {
            ...item,
          };
            addOutIntermediate(JSON.stringify(intermediateItem)).then(response => {
          });
        })
          proxy.$modal.msgSuccess("新增成功");
          goBack()
      });
    }
  });
}
// 格式为 YYYY-MM-DD HH:MM:SS 的时间字符串
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 直接出库
function directPut(){
  drugOutList.value.totalPurchaseAmount=totalPurchaseAmount.value;
  drugOutList.value.totalRetailAmount=totalRetailAmount.value;
  drugOutList.value.auditStatus=1;
  drugOutList.value.auditStaff=user.name;
  drugOutList.value.auditDate = formatDateTime(new Date());
  if(outIntermediateList.value.length==0){
    proxy.$modal.msgWarning("请添加药品");
    return;
  }
  // 药品数量不能大于库存
  outIntermediateList.value.forEach(item=>{
    listDrug({drugCode:item.drugCode}).then(response => { 
      if(item.quantity>response.rows[0].drugInventory){
        proxy.$modal.msgWarning(response.rows[0].drugGenericName+"药品数量不能大于库存"+response.rows[0].drugInventory);
        return;
      }
      proxy.$refs["drugOutRef"].validate(valid => {
        if (valid) {
          addDrugOut(drugOutList.value).then(response => {
              outIntermediateList.value.forEach(item=>{
              const intermediateItem = {
                ...item,
              };
                addOutIntermediate(JSON.stringify(intermediateItem)).then(response => {
                  // 修改库存
                  listDrug({drugCode:item.drugCode}).then(response => { 
                    const drug = response.rows[0];
                    updateDrug({
                      id: drug.id,
                      drugCode: drug.drugCode,
                      drugInventory: drug.drugInventory - item.quantity,
                    })
                  })
              });
            })
              proxy.$modal.msgSuccess("新增成功");
              goBack()
          });
        }
      });
    });
  });


}

// 审核未通过
function noApprove(){
  drugOutList.value.auditStatus=2;
  drugOutList.value.auditStaff=user.name;
  drugOutList.value.auditDate = formatDateTime(new Date());
  if (drugOutList.value.remarks == null) {
    proxy.$modal.msgError("请填写审核不通过原因");
    return;
  }
  updateDrugOut(drugOutList.value).then(response => {
          proxy.$modal.msgSuccess("审核成功");
          goBack()
  });
}

// 审核通过
function approve(){
  drugOutList.value.auditStatus=1;
  drugOutList.value.auditStaff=user.name;
  drugOutList.value.auditDate = formatDateTime(new Date());
  updateDrugOut(drugOutList.value).then(response => {
          proxy.$modal.msgSuccess("审核成功");
          goBack()
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品入库和药品中间编号为"' + _ids + '"的数据项？').then(function() {
    return delOutIntermediate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/outIntermediate/export', {
    ...queryParams.value
  }, `outIntermediate_${new Date().getTime()}.xlsx`)
}

// getList();
getDrugList();
getlistInformationList();
</script>
<style>
.order-info {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item label {
  width: 80px;
  color: #606266;
  flex-shrink: 0;
}

:deep(.el-input),
:deep(.el-select) {
  flex: 1;
}
</style>